package il.ac.braude.sona.entities;

import il.ac.braude.sona.constants.DatabaseScheme;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
/**
 * Entity for saving the data for a change request 
 * @author Ofek Ron
 * @author Avihay Avitan
 * @author Nitzan Inbar
 * @author Sasha Rozenthal
 */
public class ChangeRequest implements Serializable {
	
	
	/**
	 * Array for saving change request data, saves only the fields required for change request table
	 */
	public static final String[] summary_fields = { "Request ID","Information System","Title","Created By","Status","Date Created" };
	/**
	 * Array that holds all change request fields except for files
	 */
	public static final String[] all_fields = { "Request ID","Information System","Title","Created By","Status","Current State","Suggested Change","Explanation","Comments","Date Created" };
	/**
	 * the actual database fields for change request
	 */
	private static final String[] fields_internal = DatabaseScheme.ChangeRequest.fields;
	/**
	 * HashMap for our change request fields and the database fields
	 */
	private static final HashMap<String,String> hashFieldsTitle = new HashMap<String,String>();
	/**
	 * ArrayList for filenames for all files attached to this request
	 */
	private ArrayList<String> filenames = new ArrayList<String>();
	static {
		for (int i = 0 ; i<all_fields.length ; i++) {
			hashFieldsTitle.put(all_fields[i],fields_internal[i]);
		}
	}
	/**
	 * HashMap for the values for each field of the request
	 */
	private HashMap<String,String> values = new HashMap<String,String>();
	
	/**
	 * constructor, creates a new change request and initializes
	 * the values HasMap with the change request values  
	 * @param info  -> the result from the SQL query
	 * @param files -> the files attached to this request
	 * @throws SQLException
	 */
	public ChangeRequest(ResultSet info, ResultSet files) throws SQLException {
		for (String f : fields_internal) 
			values.put(f, info.getString(f));
		while (files.next())
			getFilenames().add(files.getString("fid"));
			
	}
	@Override
	public String toString() {
		return values.toString();
	}
	/**
	 * 
	 * @param key - the field whom we want the value for
	 * @return value at key field
	 */
	public String getValue(String key) {
		return values.get(hashFieldsTitle.get(key));
	}
	/**
	 * 
	 * @return change request id
	 */
	public String getID() {
		return values.get(fields_internal[0]);
	}
	/**
	 * 
	 * @return file names attached to this request
	 */
	public ArrayList<String> getFilenames() {
		return filenames;
	}
	@Override
	public boolean equals(Object obj) {
		if ( super.equals(obj) ) return true;
		if ( obj instanceof ChangeRequest ) 
			return getID().equals(((ChangeRequest) obj).getID());
		return false;
	}
}
